<template>
  <div class="app-container">
    <el-input v-model="listQuery.user_id" placeholder="请输入用户ID" style="width:200px;margin-bottom: 10px;" clearable></el-input>
    <el-button type="primary" @click="getList" icon="el-icon-search"   style="margin-bottom:10px;">搜索</el-button>

    <el-button class="filter-item" :type="listQuery.status === 1?'primary':''" @click="handleStatus(1)" style="margin-left:30px;margin-bottom: 10px;">待审核</el-button>
    <el-button class="filter-item" :type="listQuery.status === 2?'primary':''" @click="handleStatus(2)" style="margin-bottom:10px;">审核通过</el-button>
    <el-button class="filter-item" :type="listQuery.status === 3?'primary':''" @click="handleStatus(3)" style="margin-bottom:10px;">审核失败</el-button>

    <el-table :data="menuList" style="margin-bottom: 20px;" row-key="id" border :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="user_id" label="用户ID" > </el-table-column>
      <el-table-column prop="nickname" label="昵称" > </el-table-column>
      <el-table-column prop="avatar" label="头像" >
        <template slot-scope="scope">
          <el-popover placement="right" width="400" trigger="hover">
            <img :src="scope.row.avatar" alt="" style="max-width: 400px;max-height: 400px">
            <img slot="reference" :src="scope.row.avatar" alt="" style="width: 50px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="add_time" label="申请时间" > </el-table-column>
      <el-table-column prop="status" label="申请状态" >
        <template slot-scope="scope">
          {{ scope.row.status === 1?'待审核':'' }}
          {{ scope.row.status === 2?'审核通过':'' }}
          {{ scope.row.status === 3?'审核失败':'' }}
        </template>
      </el-table-column>
      <el-table-column prop="aaa" label="申请理由" > </el-table-column>
      <el-table-column min-width="280" label="操作" v-if="listQuery.status === 1">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleVerify(scope.row, 2)" plain>同意</el-button>
          <el-button type="primary" size="mini" @click="handleVerify(scope.row, 3)" plain>拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.perPage" @pagination="getList"/>
    <!--    v-show="total>0"-->

    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleDialogClose">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="120px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="管理员姓名" prop="admin_account">
          <el-input v-model="form.admin_account" placeholder="管理员姓名" maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="管理员密码" prop="password">
          <el-input v-model="form.password" placeholder="管理员密码"/>
        </el-form-item>
        <el-form-item label="厅的号码" prop="sociaty_no">
          <el-input v-model="form.sociaty_no" placeholder="厅的号码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { saveMenu, deleteMenu, treeMenu, updateMenu, cacheMenu, verifyMenu } from '@/api/hall/joinlistUser'

  import treeTable from '@/components/TreeTable'
  import { validateCh } from '@/utils/validate'
  import md5 from 'js-md5'

  // 常量title
  const tempDesc = {
    'id': '',
    'parentId': '',
    'menu_key': '菜单key值',
    'menu_name': '名称',
    'level': '排序',
    'icon': '图标',
    'type': '类型',
    'status': '状态',
    'parent_id': '上级菜单'
  }
  const menuTypeOptions = [
    { key: '1', display_name: '公会菜单' },
    { key: '2', display_name: '厅菜单' }
  ]
  const menuStatus = [
    { key: '1', display_name: '显示' },
    { key: '2', display_name: '隐藏' }
  ]

  export default {
    components: { treeTable },
    data() {
      const _validateCh = (rule, value, callback) => {
        if (!!value && validateCh(value)) {
          callback(new Error('不能包含中文'))
        }
        callback()
      }
      return {
        expandAll: false,
        // expandAll: true, // 是否全部展开
        expandAllTitle: '展开全部',
        tempDesc: tempDesc,
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          perPage: 10,
          status:1
        },
        columns: [
          {
            label: '菜单名称',
            key: 'title',
            width: 220,
            expand: true,
            align: 'left',
            headerAlign: 'center'
          },
          {
            label: '菜单key值',
            key: 'menu_key'
          },
          {
            label: tempDesc.type,
            key: 'type'
          },
          {
            label: '状态',
            key: 'status'
          },
          {
            label: tempDesc.icon,
            key: 'icon'
          },
          {
            label: '菜单层级',
            key: 'level'
          }
        ],
        menuList: [],
        menuTree: [],// 树形菜单
        dialogFormVisible: false,
        dialogStatus: '',
        titleMap: {
          update: '编辑',
          create: '增加'
        },
        form: {
          'admin_account': undefined,
          'password': undefined,
          'sociaty_no': undefined,
        },
        menuTypeOptions,
        menuStatus,
        optionsStatus: [{value:undefined,label: '全部状态'},{value: '1',label: '正常'},{value: '2',label: '封禁'}],
        optionsLevel: [{value:undefined,label: '全部类别'},{value: '1',label: '公会'},{value: '2',label: '厅'}],
        rules: {
          admin_account: [
            { required: true, message: '请输入管理员姓名', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入管理员密码', trigger: 'blur' }
          ],
          sociaty_no: [
            { required: true, message: '请输入厅的号码', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      // if (this.global_checkBtnPermission(['sys:menu:add', 'sys:menu:addsub', 'sys:menu:edit', 'sys:menu:delete'])) {
      //   this.columns.push({ label: '操作', key: 'operation', width: 320 })
      // }
      this.getList()
    },
    methods: {
      handleStatus(id){
        this.listQuery.status = id
        this.getList()
      },
      getList() {
        this.listLoading = true
        let urlData = '?';
        if(this.listQuery.page){ urlData = urlData + `page=${this.listQuery.page}&`}
        if(this.listQuery.perPage){ urlData = urlData + `perPage=${this.listQuery.perPage}`}
        if(this.listQuery.user_id){ urlData = urlData + `&user_id=${this.listQuery.user_id}`}
        if(this.listQuery.status){ urlData = urlData + `&status=${this.listQuery.status}`}

        treeMenu(urlData).then(response => {
          this.menuList = response.data.list
          this.total = response.data.meta.total;

          this.listLoading = false
        })
      },
      handleVerify(row, id) {
        let data = { apply_id: row.id, options:id}
        verifyMenu(data).then(response => {
          if (response.code === 200) {
            this.getList()
            this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
          }
        })
      },
      handleCreate(row) {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      handleUpdate(row) {
        this.form = []
        // this.form = Object.assign({}, row) // copy obj  此方法在这里暂时不能使用，会出错 -> 有多余参数
        this.form.admin_account = row.admin_account
        this.form.password = row.password
        this.form.sociaty_no = row.sociaty_no

        this.dialogStatus = 'update'
        this.dialogFormVisible = true

        let parentNode = this.findTreeNode(row.parentId)
        if (parentNode) {
          this.form.parent_id = parentNode.menu_name
        }

        this.form = Object.assign({}, this.form)
      },
      handleDelete(row) {
        deleteMenu(row.sociaty_id).then(response => {
          if (response.code === 200) {
            this.getList()
            this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
          }
        })
      },
      submitForm() {
        // this.form.parent_id = undefined;
        this.$refs['dataForm'].validate(valid => {
          let md5PW = md5(this.form.password)
          this.form.password = md5PW
          if (valid && this.dialogStatus === 'create') {
            saveMenu(this.form).then(response => {
              if (response.code === 200) {
                this.getList()
                this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
                this.dialogFormVisible = false
              } else {
                this.submitFail(123456)
                this.$message({
                message: response.message,
                type: 'error'
            });
              }
            })
          }else if(valid && this.dialogStatus === 'update'){
            updateMenu(this.form).then(response => {
              if (response.code === 200) {
                this.getList()
                this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
                this.dialogFormVisible = false
              } else {
                this.$message({
                message: response.message,
                type: 'error'
            });
              }
            })
          }
        })
      },
      cache(){
        cacheMenu(this.form).then(response => {
          this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });
        })
      },
      findTreeNode(id) {
        let node = this._.find(this.menuList, { id: parseInt(id) })
        return node
      },
      handleExpand() {
        this.expandAll = !this.expandAll
        this.expandAllTitle = this.expandAll ? '折叠全部' : '展开全部'
      },
      resetForm() {
        this.form = {
          'admin_account': undefined,
          'password': undefined,
          'sociaty_no': undefined,
        }
      },
      // 监听dialog关闭时的处理事件
      handleDialogClose() {
        if (this.$refs['dataForm']) {
          this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
        }
      },
      handleAvatarSuccess(res, file) {

      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }

        this.form.avatar = file
        // return isJPG && isLt2M;
      },
    }
  }
</script>
